package com.maduar.demo.netty.http.upload.decode;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.http.HttpObject;

import java.util.List;

/**
 * Description:
 *
 * @author danny.pang danny.pang@ebizprise.com
 * @date 2020-03-11 14:37
 */
public class FileDecoder extends ByteToMessageDecoder {

    private static final int fileLength = 4;
    private static final int fileNameLength = 128;

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        HttpObject decode = decode((channelHandlerContext), byteBuf);
        if (decode != null) {
            list.add(decode);
        }
    }

    protected HttpObject decode(@SuppressWarnings("UnusedParameters") ChannelHandlerContext ctx, ByteBuf in)
            throws Exception {
        if (in.readableBytes() < fileLength + fileNameLength) {
            return null;
        }

        in.markReaderIndex();
        int length = in.readInt();

        if (in.readableBytes() < length + fileNameLength) {
            in.resetReaderIndex();
            return null;
        }

        return ((HttpObject) in.readRetainedSlice(length + fileNameLength));
    }
}
